import Taro from '@tarojs/taro'
import interceptors from './interceptor'

interceptors.forEach((interceptorItem) => Taro.addInterceptor(interceptorItem))

type OptionType = {
  url: string
  data?: object | string
  method?: any
  header: object
  timeout: number
}

export default {
  baseOptions(params, method = 'GET') {
    let { url, data } = params
    // 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据，会将数据转换成 query string
    let contentType = 'application/json'
    contentType = params.contentType || contentType

    const baseUrl = process.env.TARO_APP_API

    const token = Taro.getStorageSync('token') || ''

    const option: OptionType = {
      url: baseUrl + url,
      timeout: 10000000,
      data: data,
      method: method,
      header: {
        'content-type': contentType,
        token: token,
      },
    }
    return Taro.request(option)
  },
  get(url: string, data?: object) {
    let option = { url, data }
    return this.baseOptions(option)
  },
  async post(url: string, data?: object, contentType?: string) {
    let params = { url, data, contentType }
    // const res = await this.baseOptions(params, 'POST')
    // if (res.code === 1) {
    //   return res.data
    // } else {
    //   return res
    // }
    return this.baseOptions(params, 'POST')
  },
  put(url: string, data?: object) {
    let option = { url, data }
    return this.baseOptions(option, 'PUT')
  },
  delete(url: string, data?: object) {
    let option = { url, data }
    return this.baseOptions(option, 'DELETE')
  },
}
